package tech.mhuang.ext.elasticsearch.springboot.sample;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import tech.mhuang.ext.elasticsearch.admin.ESFramework;
import tech.mhuang.ext.elasticsearch.admin.factory.IESFactory;
import tech.mhuang.ext.elasticsearch.server.annoation.ESTable;
import tech.mhuang.ext.elasticsearch.server.query.*;

import java.io.IOException;
import java.util.List;

/**
 *
 * 测试
 *
 * @author mhuang
 * @since 1.0.0
 */
@Slf4j
@Component
public class TestES implements ApplicationRunner {

    @Autowired
    private ESFramework esFramework;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            IESFactory esFactory = esFramework.getFactory("zhangsan");
            //ES新增
            IndexResponse response = esFactory.insert("{\"age\":22}", "test");
            log.info("新增1:{}", response);
            Test test = new Test();
            IndexResponse response2 = esFactory.insert(test);
            log.info("新增2:{}", response2);
            String id = response2.getId();
            test.setName("你好");
            //ES修改
            UpdateResponse response3 = esFactory.update(test, id);
            log.info("修改:{}", response3);
            //ES删除
            DeleteResponse response4 = esFactory.delete("test", id);
            log.info("删除:{}", response4);
            //ES清空索引所有数据
            AcknowledgedResponse response5 = esFactory.delete("test");
            log.info("删除索引:{}", response5);

            //获取RestHighLevelClient对象
            RestHighLevelClient client = esFactory.getClient();
            log.info("打印信息{}", client.info(RequestOptions.DEFAULT));
            ESSearchBuilder builder = new ESSearchBuilder();
            builder.indexNames(new String[]{"index"});
            builder.addCondition("age", OperatorType.EQUALS, 22);
            ESQueryAware rst = new DefaultESQuery(client).query(builder.getQueryContext());
            List<Test> testList = rst.list(Test.class);
            log.info("打印查询的信息{}",testList);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Data
    @ESTable(index = "test")
    static class Test {
        private String name = "张三";
    }
}
